import { Context } from "koa";
const { getVideoById } = require('../service/course_video.service')
const { getCourseById } = require('../service/course.service')
const { invalidVideoId, invalidCourseId, idEmpty, verifyIdError } = require('../constants/err.type')

const videoIdExist = async(ctx: Context, next: () => Promise<void>) => {
    try {
        const id = ctx.params.id
        if(!id) {
            return ctx.app.emit('error', idEmpty, ctx)
        }
        const video: any = await getVideoById(id);
        if(!video) {
            return ctx.app.emit('error', invalidVideoId, ctx)
        }
    } catch (error) {
        console.error(error)
        return ctx.app.emit('error', verifyIdError, ctx)
    }
    await next()
}

const courseIdisExist = async(ctx: Context, next: () => Promise<void>) => {
    try {
        const id = ctx.request.body.id
        if(!id) {
            return ctx.app.emit('error', idEmpty, ctx)
        }
        const course: any = await getCourseById(id);
        if(!course) {
            return ctx.app.emit('error', invalidCourseId, ctx)
        }
    } catch (error) {
        console.error(error)
        return ctx.app.emit('error', verifyIdError, ctx)
    }
    await next()
}

module.exports = {
    videoIdExist,
    courseIdisExist
}